#include "Socket.h"
#include "Tracer.h"
#include "CommandPipe.h"
#include "Utils.h"
#include <unistd.h>
#include <iostream>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define RCS_SOCKET_REMOTETRACER  "rcs.socket.remotetracer"

static void printHelpInfo()
{
    TRACE_REL("remote tracer help:\n");
    TRACE_REL("r/run : to start tracer.\n");
    TRACE_REL("q/quit: to quit.\n");
}

int main()
{
    LocalTcpSocket socket;
    if(!socket.open())
    {
        TRACE_ERR("open local socket failed:%s\n",RCS_SOCKET_REMOTETRACER);
        return -1;
    }
    if(!socket.connectLocal(RCS_SOCKET_REMOTETRACER))
    {
        TRACE_ERR("connect local socket failed:%s\n",RCS_SOCKET_REMOTETRACER);
        return -1;
    }
    printHelpInfo();
    std::string inputStr;
    while(1)
    {
        std::cin >> inputStr;
        std::cout << inputStr << std::endl;
        if ("q" == inputStr || "quit" == inputStr)
        {
            std::string tty = CommandPipe::execute("tty");
            std::string msg = "0:";
            msg += tty;
            msg = Utils::trimEndingBlank(msg);
            if (socket.writeData(msg.c_str(),msg.size())!=msg.size())
            {
                TRACE_ERR("send msg failed [%s]!\n",msg.c_str());
            }
            break;
        }
        else if("r" == inputStr || "run" == inputStr)
        {
            std::string tty = CommandPipe::execute("tty");
            std::string msg = "1:";
            msg += tty;
            msg = Utils::trimEndingBlank(msg);
            if (socket.writeData(msg.c_str(),msg.size())!=msg.size())
            {
                TRACE_ERR("send msg failed [%s]!\n",msg.c_str());
            }
        }
        else
        {
            printHelpInfo();
        }
    }
    socket.close();
    return 0;
}
